package com.wigem.approve.service;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wigem.approve.entity.*;
import com.wigem.approve.mapper.*;
import com.wigem.approve.vo.DaqEnterpriseVo;
import com.wigem.approve.vo.DaqEstateVo;
import com.wigem.approve.vo.GeApproveLogVo;
import com.wigem.framework.common.pojo.PageResult;
import com.wigem.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.wigem.approve.vo.DaqPolicyVo;
import com.wigem.framework.sa.token.core.UserInfo;
import com.wigem.framework.sa.token.core.util.SaTokenUtils;
import com.wigem.system.entity.SystemUserEntity;
import com.wigem.system.mapper.SystemUserMapper;
import com.wigem.util.MappingResultUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 楼宇政策申报Service业务层处理
 *
 * @author DH
 * @date 2024-05-27
 */
@Service
public class DaqPolicyServiceImpl implements DaqPolicyService {

    @Resource
    private DaqPolicyMapper daqPolicyMapper;
    @Resource
    private DaqEstateMapper daqEstateMapper;
    @Resource
    private DaqEnterpriseMapper daqEnterpriseMapper;

    @Resource
    private DaqEnterpriseService daqEnterpriseService;

    @Resource
    private DicEstateMapper dicEstateMapper;
    @Resource
    private DicRegionMapper dicRegionMapper;

    @Resource
    private SystemUserMapper systemUserMapper;
    @Resource
    private GeApproveLogService approveLogService;


    //街乡角色主键
    private static final String REGION = "944855eae0ab4d148cf957599d7577d8";
    //管委会角色主键
    private static final String GWH = "9214ac24575c4d2bacc0a3919e715f1b";
    //楼宇角色主键
    private static final String BUILDING = "1313907211c74fb4b6bd7c6cede72aab";

    @Override
    public List<DaqPolicyEntity> getList(DaqPolicyVo daqPolicyvo) {

        return daqPolicyMapper.selectList(query(daqPolicyvo));
    }

    @Override
    public PageResult<DaqPolicyEntity> getPageList(DaqPolicyVo daqPolicyVo) {
        UserInfo userInfo = SaTokenUtils.getLoginUserInfo();
        if (12 == userInfo.getUserId().length()) {
            daqPolicyVo.setEstateId(userInfo.getUserId());
        }
        if (StringUtils.isEmpty(daqPolicyVo.getOrderColumn())){
            daqPolicyVo.setOrderColumn("submitTime");
            daqPolicyVo.setOrderFormat("desc");
        }
        daqPolicyVo.setOrderColumn(MappingResultUtils.property2Field(daqPolicyVo.getOrderColumn(), DaqPolicyEntity.class));
        Page<DaqPolicyEntity> page = new Page<>(daqPolicyVo.getPageNo(), daqPolicyVo.getPageSize());
        IPage<DaqPolicyEntity> mappingList = daqPolicyMapper.getPageList(page, daqPolicyVo);
        return new PageResult<>(mappingList.getRecords(), mappingList.getTotal());
    }


    @Override
    public DaqPolicyEntity getEntity(String id) {
        return daqPolicyMapper.selectById(id);
    }

    @Override
    public void add(DaqPolicyVo daqPolicyVo) {
        DaqPolicyEntity daqPolicyEntity = new DaqPolicyEntity();
        BeanUtils.copyProperties(daqPolicyVo, daqPolicyEntity);
        daqPolicyEntity.create();
        daqPolicyMapper.insert(daqPolicyEntity);
    }


    @Override
    public void update(DaqPolicyVo daqPolicyVo) {
        DaqPolicyEntity daqPolicyEntity = new DaqPolicyEntity();
        BeanUtils.copyProperties(daqPolicyVo, daqPolicyEntity);
        daqPolicyMapper.updateById(daqPolicyEntity);
    }

    @Override
    public Boolean validatePolicy(DaqPolicyVo daqPolicyVo) {
        UserInfo userInfo = SaTokenUtils.getLoginUserInfo();
        DaqPolicyVo query = new DaqPolicyVo();
        query.setRemoveMark("0");
        query.setReportId(daqPolicyVo.getReportId());
        query.setCreateUser(userInfo.getUserId());
        List<DaqPolicyEntity> list = getList(query);
        return !(list.size() > 0);
    }


    @Override
    public String save(DaqPolicyVo daqPolicyVo) {
        // 验证当前报告期的当前楼宇是否申报过了，不允许重复保存
        int result = 0;
        if (!validatePolicy(daqPolicyVo)) {
            return "";
        }
        UserInfo userInfo = SaTokenUtils.getLoginUserInfo();
        DaqPolicyEntity daqPolicyEntity = new DaqPolicyEntity();
        BeanUtils.copyProperties(daqPolicyVo, daqPolicyEntity);
        if (StringUtils.isEmpty(daqPolicyVo.getId())) {
            daqPolicyEntity.create();

            SystemUserEntity user = systemUserMapper.getEntity(userInfo.getUserId());
            DicEstateEntity dicEstate = dicEstateMapper.getEntity(user.getUserName());
            DicRegionEntity dicRegion = dicRegionMapper.getEntity(dicEstate.getRegionId());

            daqPolicyEntity.setRegionId(dicEstate.getRegionId());
            daqPolicyEntity.setRegionName(dicRegion.getRegionName());
            daqPolicyEntity.setEstateId(dicEstate.getId());
            daqPolicyEntity.setEstateName(user.getRealName());
            daqPolicyEntity.setCreateUser(userInfo.getUserId());
            daqPolicyEntity.setCreateTime(new Date());
            daqPolicyEntity.setApproveId("0");
            result = daqPolicyMapper.insert(daqPolicyEntity);
        } else {
            result = daqPolicyMapper.updateById(daqPolicyEntity);
            //审批日志只有在街乡角色和管委会角色修改时才会添加
            if (REGION.equals(userInfo.getRoleIds()) || GWH.equals(userInfo.getRoleIds())) {
                GeApproveLogVo approveLogVo = new GeApproveLogVo();
                approveLogVo.setUserId(userInfo.getUserId());
                approveLogVo.setRealName(userInfo.getRealName());
                approveLogVo.setUserUnit(userInfo.getRealName());
                approveLogVo.setOperateInfoId(daqPolicyEntity.getId());
                approveLogVo.setOperateProcessName(daqPolicyVo.getActionName());
                approveLogVo.setOperateContent(approveLogVo.getOperateProcessName());
                approveLogVo.setOperateTime(new Date());
                approveLogService.save(approveLogVo);
            }
        }
        return result > 0 ? daqPolicyEntity.getId() : "";
    }

    //验证当前申报记录中是否提交了楼宇和企业信息
    @Override
    public Boolean validateEstateAndEnterprise(String policyId) {
        Boolean result = false;
        //填报人、联系电话必填
        DaqPolicyEntity entity = daqPolicyMapper.getEntity(policyId);
        if (StringUtils.isEmpty(entity.getFillPerson()) ||StringUtils.isEmpty(entity.getFillPhone())) {
            return result;
        }
        //楼宇信息必填
        DaqEstateVo daqEstateVo = new DaqEstateVo();
        daqEstateVo.setPolicyId(policyId);
        List<DaqEstateEntity> estateList = daqEstateMapper.getList(daqEstateVo);
        //企业信息必填
        DaqEnterpriseVo daqEnterpriseVo = new DaqEnterpriseVo();
        daqEnterpriseVo.setPolicyId(policyId);
        List<DaqEnterpriseEntity> enterpriseList = daqEnterpriseService.getList(daqEnterpriseVo);
        if (estateList.size() > 0 && enterpriseList.size() > 0) {
            result = true;
        }
        return result;
    }

    @Override
    public int submit(String policyId) {
        int result = 0;
        int node = 0;
        //验证当前申报记录中是否提交了楼宇和企业信息
        if (!this.validateEstateAndEnterprise(policyId)) {
            return result;
        }

        DaqPolicyEntity daqPolicyEntity = daqPolicyMapper.getEntity(policyId);
        //初审状态
        if ("0".equals(daqPolicyEntity.getApproveId()) || "3".equals(daqPolicyEntity.getApproveId()) || "6".equals(daqPolicyEntity.getApproveId())) {
            //提交后为街乡待审核状态
            daqPolicyEntity.setApproveId("1");
            node = 1;
        }
        //复审状态
        if ("7".equals(daqPolicyEntity.getApproveId()) || "10".equals(daqPolicyEntity.getApproveId()) || "13".equals(daqPolicyEntity.getApproveId())) {
            //提交后为街乡待审核状态
            daqPolicyEntity.setApproveId("8");
            node = 2;
        }
        daqPolicyEntity.setSubmitTime(new Date());

        result = daqPolicyMapper.updateById(daqPolicyEntity);
        if (result > 0) {
            UserInfo userInfo = SaTokenUtils.getLoginUserInfo();
            GeApproveLogVo approveLogVo = new GeApproveLogVo();
            approveLogVo.setUserId(userInfo.getUserId());
            approveLogVo.setRealName(userInfo.getRealName());
            approveLogVo.setUserUnit(userInfo.getRealName());
            approveLogVo.setOperateInfoId(daqPolicyEntity.getId());
            approveLogVo.setOperateProcessName(node == 1 ? "楼宇初审提交" : "楼宇复审补充提交");
            approveLogVo.setOperateContent(approveLogVo.getOperateProcessName());
            approveLogVo.setOperateTime(new Date());
            approveLogService.save(approveLogVo);
        }
        return result;
    }


    @Override
    public int delete(String id) {
        return daqPolicyMapper.deleteById(id);
    }


    @Override
    public int remove(String id) {
        return daqPolicyMapper.remove(id);
    }


    public LambdaQueryWrapperX<DaqPolicyEntity> query(DaqPolicyVo daqPolicyVo) {

        LambdaQueryWrapperX<DaqPolicyEntity> daqPolicyEntityLambdaQueryWrapperX = new LambdaQueryWrapperX<>();
        daqPolicyEntityLambdaQueryWrapperX = daqPolicyEntityLambdaQueryWrapperX
                .eqIfPresent(DaqPolicyEntity::getId, daqPolicyVo.getId())
                .eqIfPresent(DaqPolicyEntity::getEstateId, daqPolicyVo.getEstateId())
                .likeIfPresent(DaqPolicyEntity::getEstateName, daqPolicyVo.getEstateName())
                .eqIfPresent(DaqPolicyEntity::getReportId, daqPolicyVo.getReportId())
                .eqIfPresent(DaqPolicyEntity::getReportYear, daqPolicyVo.getReportYear())
                .eqIfPresent(DaqPolicyEntity::getRegionId, daqPolicyVo.getRegionId())
                .likeIfPresent(DaqPolicyEntity::getRegionName, daqPolicyVo.getRegionName())
                .eqIfPresent(DaqPolicyEntity::getFillPerson, daqPolicyVo.getFillPerson())
                .eqIfPresent(DaqPolicyEntity::getFillPhone, daqPolicyVo.getFillPhone())
                .eqIfPresent(DaqPolicyEntity::getCreateUser, daqPolicyVo.getCreateUser())
                .eqIfPresent(DaqPolicyEntity::getCreateTime, daqPolicyVo.getCreateTime())
                .eqIfPresent(DaqPolicyEntity::getUpdateUser, daqPolicyVo.getUpdateUser())
                .eqIfPresent(DaqPolicyEntity::getUpdateTime, daqPolicyVo.getUpdateTime())
                .eqIfPresent(DaqPolicyEntity::getSubmitUser, daqPolicyVo.getSubmitUser())
                .eqIfPresent(DaqPolicyEntity::getSubmitTime, daqPolicyVo.getSubmitTime())
                .eqIfPresent(DaqPolicyEntity::getPolicyType, daqPolicyVo.getPolicyType())
                .eqIfPresent(DaqPolicyEntity::getRemoveMark, daqPolicyVo.getRemoveMark())
        ;
        return daqPolicyEntityLambdaQueryWrapperX;
    }


}
